package door.smartlift.top.common.utils;
import com.google.gson.*;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

public class JsonUtil {
	public static String object2json(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(string2json(obj.toString())).append("\"");
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			json.append(bean2json(obj));
		}
		return json.toString();
	}

	public static String bean2json(Object bean) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		PropertyDescriptor[] props = null;
		try {
			props = Introspector.getBeanInfo(bean.getClass(), Object.class)
					.getPropertyDescriptors();
		} catch (IntrospectionException e) {
		}
		if (props != null) {
			for (int i = 0; i < props.length; i++) {
				try {
					String name = object2json(props[i].getName());
					String value = object2json(props[i].getReadMethod().invoke(
							bean));
					json.append(name);
					json.append(":");
					json.append(value);
					json.append(",");
				} catch (Exception e) {
				}
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String list2json(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String array2json(Object[] array) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String map2json(Map<?, ?> map) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	public static String set2json(Set<?> set) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	public static String string2json(String s) {
		if (s == null) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}
   public static JsonObject parseJson(String json){
        JsonParser parser = new JsonParser();
        JsonObject jsonObj = parser.parse(json).getAsJsonObject();
        return jsonObj;
    }

    /**
     * 根据json字符串返回Map对象
     * @param json
     * @return
     */
    public static   Map<String,Object> stringToMap(String json){
        return toMap(parseJson(json));
    }

    /**
     * 将JSONObjec对象转换成Map-List集合
     * @param json
     * @return
     */
    public static Map<String, Object> toMap(JsonObject json){
        Map<String, Object> map = new HashMap<String, Object>();
        Set<Map.Entry<String, JsonElement>> entrySet = json.entrySet();
        for (Iterator<Map.Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ){
            Map.Entry<String, JsonElement> entry = iter.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            if(value instanceof JsonArray) {
				map.put(key, toList((JsonArray) value));
			} else if(value instanceof JsonObject) {
				map.put(key, toMap((JsonObject) value));
			} else {
				String val = value.toString();
				boolean cc=  val.startsWith("\"");
				if (cc) {
					val = val.substring(1, val.length() - 1);
				}
				map.put(key, val);
			}
        }
        return map;
    }

    /**
     * 将JSONArray对象转换成List集合
     * @param json
     * @return
     */
    public static List<Object> toList(JsonArray json){
        List<Object> list = new ArrayList<Object>();
        for (int i=0; i<json.size(); i++){
            Object value = json.get(i);
            if(value instanceof JsonArray){
                list.add(toList((JsonArray) value));
            }
            else if(value instanceof JsonObject){
                list.add(toMap((JsonObject) value));
            }
            else{
                list.add(value);
            }
        }
        return list;
    }

    /**
     * 将json格式转化成对象
     * @param json
     * @return
     */
    /*public static <T> T stringToObj(String json,Class<T> tClass) {
        Gson gson = new Gson();
        if ("java.util.Map".equals(tClass.getName())){
          return  (T)stringToMap(json);
        }
      return  gson.fromJson(json,tClass);
    }*/
    /**
     * 将对象转化成json字符串
     * @return
     */
    public static String objToJson(Object object) {
        Gson gson = new Gson();
        return  gson.toJson(object);
    }

    public static <T> T getObjectFromJSONString(String json, Class<T> clazz) throws NoSuchFieldException, IllegalAccessException, InstantiationException {

        T t= clazz.newInstance();
        String[] listJson = spiltString(json);
        for (int i = 0; i < listJson.length; i++) {
            String lists=listJson[i].split(":")[0];
            try {
                if (lists.startsWith("")){
                    lists=lists.substring(1,lists.length()-1);
                }
                Field field = clazz.getDeclaredField(getNewStringName(lists));
                field.setAccessible(true);
                if (field.getType().equals(Integer.class)){
                    field.set(t,Integer.valueOf(listJson[i].split(":")[1]));
                }else {
                    String lists2=listJson[i].substring(listJson[i].indexOf(":")+1).replace("\\","");
                    if(lists2.startsWith("")) {
                        try {
                            Integer.parseInt(lists2);
                        }catch (NumberFormatException e){
                            field.set(t, lists2.substring(1, lists2.length() - 1));
                        }
                    }
                }
            }catch (NoSuchFieldException e){
                e.printStackTrace();
            }
        }
        return  t;

    }

    public static String[] spiltString(String jsonParme) {
        String[] result = jsonParme.split(",");
        if (result !=null && result.length>0) {
            result[0] = String.copyValueOf(result[0].toCharArray(), 1, result[0].toCharArray().length - 1);
            result[result.length - 1] = String.copyValueOf(result[result.length - 1].toCharArray(), 0, result[result.length - 1].toCharArray().length - 2);
        }
        return result;
    }

    public static String getNewStringName(String jsonParme) {
        String[] aa = jsonParme.split("_");
        String returnName = null;
        if (aa !=null && aa.length>0) {
            for (int i = 0; i < aa.length; i++) {
                if (i == 0) {
                    returnName = aa[0];
                } else {
                    char[] cs = aa[i].toCharArray();
                    cs[0] -= 32;
                    returnName = returnName + String.valueOf(cs);
                }
            }
        }else {
            returnName=jsonParme;
        }
        return  returnName;
    }

	public static String objToString(Object object){
		Gson gson = new Gson();
		return  gson.toJson(object);
	}

	public static Object stringToObj(String json,Class tClass){
		Gson gson = new Gson();
		return  gson.fromJson(json, tClass);
	}


}
